package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

import java.util.Comparator;
import java.util.TreeSet;

public class OtherTeacherDao  implements BaseTeacherDao {
    //private static ArrayList<Teacher> teachers = new ArrayList<>();
    private static TreeSet<Teacher> teachers=new TreeSet<>(new Comparator<Teacher>() {
        @Override
        public int compare(Teacher o1, Teacher o2) {
            int i = Integer.parseInt(o2.getAge()) - Integer.parseInt(o1.getAge());
            int j = i == 0 ? o1.getName().compareTo(o2.getName()) : i;
            return j;
        }
    });

    static {
        Teacher t1 = new Teacher("itheima001", "张三", "23", "1997-10-10");
        Teacher t2 = new Teacher("itheima002", "李四", "23", "1997-10-10");
        teachers.add(t1);
        teachers.add(t2);
    }

    public boolean addTeacher(Teacher teacher) {
        teachers.add(teacher);
        return true;

    }

   /* public Teacher[] findAllTeacher() {
        Teacher[] teacher=new  Teacher[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher1 = teachers.get(i);
            teacher[i]=teacher1;
        }
        return teacher;
    }*/
   public Teacher[] findAllTeacher() {
       Teacher[] teacher=new Teacher[teachers.size()];
       Teacher[] tea = OtherTeacherDao.teachers.toArray(teacher);
       return tea;
   }

   /* public void deleteTeacher(String sid) {
        int index = getIndex(sid);
        teachers.remove(index);
    }*/
   public void deleteTeacher(String sid) {
       int index = getIndex(sid);
       Teacher[] teacher=new Teacher[teachers.size()];
       Teacher[] tea = OtherTeacherDao.teachers.toArray(teacher);
       for (int i = 0; i < tea.length; i++) {
           if (tea[index].getSid().equals(tea[i].getSid())){
               teachers.remove(tea[index]);
           }
       }
   }

   /* public void updateTeacher(String sid, Teacher teacher) {
        int index = getIndex(sid);
        teachers.set(index,teacher);
    }*/
   public void updateTeacher(String sid, Teacher teacher) {
       int index = getIndex(sid);
       Teacher[] t=new Teacher[teachers.size()];
       Teacher[] tea = OtherTeacherDao.teachers.toArray(t);
       for (int i = 0; i < tea.length; i++) {
           if (tea!=null&&tea[index].getSid().equals(tea[i].getSid())){
               tea[index]=teacher;
               deleteTeacher(tea[i].getSid());
           }
       }
       for (int i = 0; i < tea.length; i++) {
           teachers.add(tea[i]);
       }
   }

    public int getIndex(String sid) {
        int index = -1;
        Teacher[] t=new Teacher[teachers.size()];
        Teacher[] tea = OtherTeacherDao.teachers.toArray(t);
        for (int i = 0; i < tea.length; i++) {
            Teacher teacher = tea[i];
            if (teacher != null && sid.equals(teacher.getSid())) {
                index = i;
            }
        }
        return index;
    }
}
